from requests.packages.urllib3.exceptions import InsecureRequestWarning

# !usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: lenovo by amidoufu
@file: amidoufu.py
@time: 2020/05/06
@function:
"""
import requests
import time
import os
import re
import sys
import emoji
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

__headers_web = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
}

class quanju:
    shipinmingcheng = ""
    dir = ""
    jishu = 0


def chushi():
    zuozhelianjie = input("输入作者链接：")
    res = requests.get(zuozhelianjie, headers=__headers_web, verify=False)
    html = res.text
    zuozhemingcheng_find = r'txt2\">(.+?)<'
    zuozhemingcheng = re.findall(zuozhemingcheng_find, html)
    if not os.path.exists("./火力视频data/" + zuozhemingcheng[0]):
        os.makedirs("./火力视频data/" + zuozhemingcheng[0])
    quanju.dir = "火力视频data/" + zuozhemingcheng[0] + "/"

    shipinliebiao_find = r'/watch.php(.+?)\"'
    shipinliebiao = re.findall(shipinliebiao_find, html)


    continuation_find = r'continuation.=.\"(.+?)\";'
    continuation = re.findall(continuation_find, html)
    if continuation == []:
        continuation = ""
    else:
        continuation = continuation[0]

    itct_find = r'itct.=.\"(.+?)\";'
    itct = re.findall(itct_find, html)
    if itct == []:
        itct = ""
    else:
        itct = itct[0]

    page_cl_find = r'page_cl.=.\"(.+?)\";'
    page_cl = re.findall(page_cl_find, html)
    if page_cl == []:
        page_cl = ""
    else:
        page_cl = page_cl[0]

    checksum_find = r'checksum.=.\"(.+?)\";'
    checksum = re.findall(checksum_find, html)
    if checksum == []:
        checksum = ""
    else:
        checksum = checksum[0]

    channel_id_find = r'channel_id.=.\"(.+?)\";'
    channel_id = re.findall(channel_id_find, html)
    if channel_id == []:
        channel_id = ""
    else:
        channel_id = channel_id[0]




    if shipinliebiao != []:
        print("此次共:" + str(len(shipinliebiao)) + "个视频")
        for shipinliebiao_jici in range(0, len(shipinliebiao)):
            shipinlianjie = "https://fuli201.fuliget.net/watch.php" + shipinliebiao[shipinliebiao_jici]
            time.sleep(10)
            huoqu_id(shipinlianjie)
        #data = "continuation=" + continuation[0] + "&itct=" + itct[0] + "&page_cl=" + page_cl[0] + "&checksum=" + checksum[0] + "&channel_id=" + channel_id[0] + "&token=" + token[0] + "&sp=" + sp_find[0] + "&words=" + words[0]
        data = {'continuation': continuation,
                'itct': itct,
                'page_cl': page_cl,
                'checksum': checksum,
                'channel_id': channel_id}
        res = requests.post("https://fuli201.fuliget.net/channel_next.php", headers=__headers_web, verify=False,
                            data=data)
        html = res.text

        shipinliebiao_find = r'<a.href=\".(.+?)\"'
        shipinliebiao = re.findall(shipinliebiao_find, html)

        continuation_find = r'continuation.=.\"(.+?)\";'
        continuation = re.findall(continuation_find, html)
        if continuation == []:
            continuation = ""
        else:
            continuation = continuation[0]

        itct_find = r'itct.=.\"(.+?)\";'
        itct = re.findall(itct_find, html)
        if itct == []:
            itct = ""
        else:
            itct = itct[0]

        page_cl_find = r'page_cl.=.\"(.+?)\";'
        page_cl = re.findall(page_cl_find, html)
        if page_cl == []:
            page_cl = ""
        else:
            page_cl = page_cl[0]

        checksum_find = r'checksum.=.\"(.+?)\";'
        checksum = re.findall(checksum_find, html)
        if checksum == []:
            checksum = ""
        else:
            checksum = checksum[0]

        channel_id_find = r'channel_id.=.\"(.+?)\";'
        channel_id = re.findall(channel_id_find, html)
        if channel_id == []:
            channel_id = ""
        else:
            channel_id = channel_id[0]

    while shipinliebiao != []:
        print("此次共:" + str(len(shipinliebiao)) + "个视频")
        for shipinliebiao_jici in range(0, len(shipinliebiao)):
            shipinlianjie = "https://fuli201.fuliget.net/watch.php" + shipinliebiao[shipinliebiao_jici]
            time.sleep(5)
            huoqu_id(shipinlianjie)
        data = {'continuation': continuation,
                'itct': itct,
                'page_cl': page_cl,
                'checksum': checksum,
                'channel_id': channel_id}
        res = requests.post("https://fuli201.fuliget.net/channel_next.php", headers=__headers_web, verify=False,
                            data=data)
        html = res.text

        shipinliebiao_find = r'<a.href=\".(.+?)\"'
        shipinliebiao = re.findall(shipinliebiao_find, html)

        continuation_find = r'continuation.=.\"(.+?)\";'
        continuation = re.findall(continuation_find, html)
        if continuation == []:
            continuation = ""
        else:
            continuation = continuation[0]

        itct_find = r'itct.=.\"(.+?)\";'
        itct = re.findall(itct_find, html)
        if itct == []:
            itct = ""
        else:
            itct = itct[0]

        page_cl_find = r'page_cl.=.\"(.+?)\";'
        page_cl = re.findall(page_cl_find, html)
        if page_cl == []:
            page_cl = ""
        else:
            page_cl = page_cl[0]

        checksum_find = r'checksum.=.\"(.+?)\";'
        checksum = re.findall(checksum_find, html)
        if checksum == []:
            checksum = ""
        else:
            checksum = checksum[0]

        channel_id_find = r'channel_id.=.\"(.+?)\";'
        channel_id = re.findall(channel_id_find, html)
        if channel_id == []:
            channel_id = ""
        else:
            channel_id = channel_id[0]




def huoqu_id(shipinlianjie):
    quanju.jishu += 1
    #res = requests.get(shipinlianjie, headers=__headers_web,verify=False)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            res = requests.get(shipinlianjie, headers=__headers_web,verify=False)
            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
            # res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            print("HTTPError")
            time.sleep(3)
        except requests.exceptions.ConnectionError:
            print("ConnectionError")
            time.sleep(3)
        except requests.exceptions.ChunkedEncodingError:
            print("ChunkedEncodingError")
            time.sleep(3)
        except:
            print("Unfortunitely -- An Unknow Error Happened")
            time.sleep(3)
    html = res.text
    shipin_id_find = r'var.item_id.=.\'(.+?)\';'
    shipin_id_1 = re.findall(shipin_id_find, html)
    shipin_id = shipin_id_1[0]
    shipinmingcheng_find = r'var.title.=.\'(.+?)\';'
    shipinmingcheng_1 = re.findall(shipinmingcheng_find, html)
    shipinmingcheng_2 = shipinmingcheng_1[0]
    shipinmingcheng_3 = re.sub(r'[\\/:*?"<>|\r\n]+', "", shipinmingcheng_2)[0:66]
    emoji_str = emoji.demojize(shipinmingcheng_3)
    quanju.shipinmingcheng = re.sub(r':(.*?):', '', emoji_str).strip() + "_" + shipin_id
    video_down = quanju.dir + quanju.shipinmingcheng + ".mp4"
    if os.path.exists(video_down):
        print(str(quanju.jishu) + ">" + "\n视频:" + quanju.shipinmingcheng + "------已存在")
        print("\n")
        return
    time.sleep(5)
    huoqu_xiazaidizhi(shipin_id)

def huoqu_xiazaidizhi(shipin_id):
    #res = requests.get("https://fuli201.fuliget.net/ajax/ajax.php?type=videos&v=" + shipin_id, headers=__headers_web,verify=False)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            res = requests.get("https://fuli201.fuliget.net/ajax/ajax.php?type=videos&v=" + shipin_id, headers=__headers_web,verify=False)
            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
            # res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            print("HTTPError")
            time.sleep(3)
        except requests.exceptions.ConnectionError:
            print("ConnectionError")
            time.sleep(3)
        except requests.exceptions.ChunkedEncodingError:
            print("ChunkedEncodingError")
            time.sleep(3)
        except:
            print("Unfortunitely -- An Unknow Error Happened")
            time.sleep(3)
    html = res.text
    xiazailianjie_find = r'<td><a.target=\"_blank\".href=\"(.+?)\"'
    xiazailianjie_1 = re.findall(xiazailianjie_find, html)
    xiazailianjie = xiazailianjie_1[0]
    i =0
    while xiazailianjie =="":
        i += 1
        xiazailianjie = xiazailianjie_1[i]
    time.sleep(5)
    huoqu_zhenshilianjie(xiazailianjie)


def huoqu_zhenshilianjie(xiazailianjie):
    #res = requests.get(xiazailianjie, headers=__headers_web,verify=False)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            res = requests.get(xiazailianjie, headers=__headers_web,verify=False)
            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
            # res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            print("HTTPError")
            time.sleep(3)
        except requests.exceptions.ConnectionError:
            print("ConnectionError")
            time.sleep(3)
        except requests.exceptions.ChunkedEncodingError:
            print("ChunkedEncodingError")
            time.sleep(3)
        except:
            print("Unfortunitely -- An Unknow Error Happened")
            time.sleep(3)
    html = res.text
    zhenshilianjie_find = r'url=(.+?)\"'
    zhenshilianjie_1 = re.findall(zhenshilianjie_find, html)
    zhenshilianjie = zhenshilianjie_1[0]
    time.sleep(5)
    huoqu_zhenshixiazaidizhi(zhenshilianjie)


def huoqu_zhenshixiazaidizhi(zhenshilianjie):
    #res = requests.get(zhenshilianjie, headers=__headers_web,verify=False)
    while True:  # 一直循环，知道访问站点成功
        try:
            # 以下except都是用来捕获当requests请求出现异常时，
            # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
            res = requests.get(zhenshilianjie, headers=__headers_web,verify=False)
            # res = requests.get(w_url, headers=__headers_mobile, verify=False)
            # res.raise_for_status()
            break
        except requests.exceptions.HTTPError:
            print("HTTPError")
            time.sleep(3)
        except requests.exceptions.ConnectionError:
            print("ConnectionError")
            time.sleep(3)
        except requests.exceptions.ChunkedEncodingError:
            print("ChunkedEncodingError")
            time.sleep(3)
        except:
            print("Unfortunitely -- An Unknow Error Happened")
            time.sleep(3)
    html = res.text
    xiazaidizhi_find = r'下载地址：<a.href=\"(.+?)\">'
    xiazaidizhi_1 = re.findall(xiazaidizhi_find, html)
    i = 0
    while xiazaidizhi_1 == []:
        i += 1
        print(str(quanju.jishu) + ">" + "\n" + quanju.shipinmingcheng + "------准备尝试再次获取下载地址.")
        print("正在尝试第" + str(i) + "次获取下载地址")
        # res = requests.get(zhenshilianjie, headers=__headers_web,verify=False)
        while True:  # 一直循环，知道访问站点成功
            try:
                # 以下except都是用来捕获当requests请求出现异常时，
                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                res = requests.get(zhenshilianjie, headers=__headers_web, verify=False)
                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                # res.raise_for_status()
                break
            except requests.exceptions.HTTPError:
                print("HTTPError")
                time.sleep(3)
            except requests.exceptions.ConnectionError:
                print("ConnectionError")
                time.sleep(3)
            except requests.exceptions.ChunkedEncodingError:
                print("ChunkedEncodingError")
                time.sleep(3)
            except:
                print("Unfortunitely -- An Unknow Error Happened")
                time.sleep(3)
        html = res.text
        xiazaidizhi_find = r'下载地址：<a.href=\"(.+?)\">'
        xiazaidizhi_1 = re.findall(xiazaidizhi_find, html)
        if i == 3:
            break
        time.sleep(10)
    if xiazaidizhi_1 == []:
        print("------没有下载地址已跳过.")
        return
    xiazaidizhi = xiazaidizhi_1[0]
    time.sleep(5)
    xiazaishipin(xiazaidizhi)

def xiazaishipin(xiazaidizhi, retry=3):
    '''
    下载视频,显示进度

    :param index:       视频序号
    :param username:    用户名
    :param name:        视频名
    :param url:         视频地址
    :param retry:       重试次数

    :return:            None
    '''

    print(str(quanju.jishu) + ">" + "\n正在下载视频:" + quanju.shipinmingcheng)
    video_down = quanju.dir + quanju.shipinmingcheng + ".mp4"
    if os.path.exists(video_down):
        print("视频已存在")
        return
    else:
            print("视频正在下载")
    try:
        #video_response = requests.get(xiazaidizhi, headers=__headers_web, timeout=15)
        while True:  # 一直循环，知道访问站点成功
            try:
                # 以下except都是用来捕获当requests请求出现异常时，
                # 通过捕获然后等待网络情况的变化，以此来保护程序的不间断运行
                video_response = requests.get(xiazaidizhi, headers=__headers_web, timeout=15)
                # res = requests.get(w_url, headers=__headers_mobile, verify=False)
                # res.raise_for_status()
                break
            except requests.exceptions.HTTPError:
                print( "HTTPError")
                time.sleep(3)
            except requests.exceptions.ConnectionError:
                print( "ConnectionError")
                time.sleep(3)
            except requests.exceptions.ChunkedEncodingError:
                print( "ChunkedEncodingError")
                time.sleep(3)
            except:
                print( "Unfortunitely -- An Unknow Error Happened")
                time.sleep(3)


        # 保存视频，显示下载进度
        if video_response.status_code == 200:
            video_size = int(video_response.headers['Content-Length'])
            if video_size/1024000 >= 10000:
                print("视频超过10G已跳过")
                print("\n")
                return
            else:
                with open(video_down, 'wb') as f:
                    data_length = 0
                    for data in video_response.iter_content(chunk_size=1024):
                        data_length += len(data)
                        f.write(data)
                        done = int(50 * data_length / video_size)
                        sys.stdout.write("\r下载进度: [%s%s]" % (
                            '█' * done, ' ' * (50 - done)))
                        sys.stdout.flush()
            print("\n")



        # 失败重试3次，超过放弃
        elif video_response.status_code != 200 and retry:
            retry -= 1
            xiazaishipin(xiazaidizhi, retry)
        else:
            return
    except Exception as e:
        print('download failed,', quanju.shipinmingcheng, e)
        return None


if __name__ == "__main__":
    chushi()